//playlist var that will hold the song objects
var playlist;
        
//function to populate playlist
function populatePlaylist(song){
	var firstPlay = "false";
	if (playlist == null){
		firstPlay = "true";
		playlist = new Array();
	}
	playlist.push(song);
	
	playlist = playlist.reverse();
	
	if(firstPlay == "true"){
		firstPlay = "false";
		cmdBtnPressed();
	}
}
        
var STOPPED = "STOPPED";
var PLAYING = "PLAYING";
var PAUSED = "PAUSED";

var loadingSplashOn = "false";  // var to keep track if loading is on
var previousPercent = 0;
        
//Player Status
var playerStatus = STOPPED; /* PLAYING, PAUSED, STOPPED */
        	
// Audio player
var my_media = null;
var mediaTimer = null; 
var totalDuration;
var autoLoadNextSong = "false";
		
// Play audio 
function playAudio(src) { 
	previousPercent = 0;
	//Put a loading screen
	displayLoadingSplash();
	
	autoLoadNextSong = "false";
	
	//If currently playing stop the audio 
	if (my_media){
		stopAudio();
	}
	
    // Create Media object from src
    my_media = new Media(src, playCompleted, onError);
    my_media.play();
    
 // Update my_media position every second
    if (mediaTimer == null) {
        mediaTimer = setInterval(function() {
            // get my_media position
            my_media.getCurrentPosition(
                // success callbacknextBtnPressed
                function(position) {
                    if (position > -1) {
                        setProgress((position/totalDuration)*100);
                    }
                },
                // error callback
                function(e) {
                    console.log("Error getting pos=" + e);
                    setProgress(0);
                }
            );
        }, 1000);
    }
}

// progress bar
function setProgress(percent){
	checkBuffering(percent);
	if (percent > 90)
	   autoLoadNextSong = "true";

	percent = Math.round(percent);
	$("#progress").width(""+percent+"%");
}

//function to show Loading splash
function displayLoadingSplash(){
	loadingSplashOn = "true";
	$("#loading_splash").removeClass("display_none");
}

//function to remove Loading splash
function removeLoadingSplash(){
	loadingSplashOn = "false";
	$("#loading_splash").addClass("display_none");
}

//check buffering status
function checkBuffering(percent){
	
	//if stuck at same location...
	if (previousPercent == percent){
		//if stuck in same location we want to show loading
		if (playerStatus == PLAYING){ 
			displayLoadingSplash();
		}
	}
	
	// added for optimization
	if (loadingSplashOn == "true"){
		if (percent > previousPercent){
			removeLoadingSplash();
		}
	}
	previousPercent = percent;
}

// Pause audio 
function pauseAudio() {
	if (my_media) {
		my_media.pause();
    }
}

// Resume audio 
function resumeAudio(){
	if(my_media){
		my_media.play();
	}
	showNotification();
}

// Stop audio 
function stopAudio() {
    if (my_media) {
        my_media.stop();
        my_media.release();
		my_media = null;
		mediaTimer = null;
    }
}

// when done playing 
function playCompleted() {
	
    if (autoLoadNextSong == "true"){
		//alert("PC and ns");
		autoLoadNextSong = "false";
		nextSong();
	}
}

// onError Callback 
function onError(error) {
  //Intentially Left Blank
}

function playSong(song){
  this.totalDuration = song.Length;
  
  playAudio(song.SongUrl);
  
  $("#title").html(song.Title);
  $("#artist").html(song.Artist);
  
  $("#clipart").css('background-image', "url('"+song.AlbumImageUrl+"')");
  showNotification();
}

function playCurrentSong(){
	if (playlist.length < 3){ // if we have less than 3 songs we will fetch more songs
		loadPlaylist(); // make another ajax call to load songs
	}
	
	var song = playlist.pop();
	//alert('URL: ' + song.SongUrl);
	playSong(song);
}

function nextSong(){
	playCurrentSong();
}

function changeButton(type){
	switch(type){
	case PAUSED:
		$("#cmd_btn").removeClass("btn btn_pause");
		$("#cmd_btn").addClass("btn btn_play");
		playerStatus = PAUSED;
		break;
	case PLAYING:
		$("#cmd_btn").removeClass("btn btn_play");
		$("#cmd_btn").addClass("btn btn_pause");
		playerStatus = PLAYING;
		break;
	}	
}

/*
  Command button that either plays or pauses the music
*/
function cmdBtnPressed(){
	if (playerStatus == PLAYING){
		pauseAudio();
		changeButton(PAUSED);
	}
	else if (playerStatus == STOPPED){
		playCurrentSong();
		changeButton(PLAYING);
	}
	else if (playerStatus == PAUSED){
		resumeAudio();
		changeButton(PLAYING);
	}
}

function nextBtnPressed(){
		autoLoadNextSong = false;
		if (playerStatus == PLAYING)
		      nextSong();
		autoLoadNextSong = true;
}

//Clear Notificaiton Bar
function removeNotification(){
	window.plugins.statusBarNotification.clear();
}

//Notification Bar
function showNotification(){
	var title = $('#title').html();
	window.plugins.statusBarNotification.notify("Sarangi", title);
}

//This function should be called when app will be quitting
function appExiting(){
	removeNotification();
}